<?php
/**
 * author:歪妻
 * Date: 2020/11/2 0002
 */

/**
 * 获取项目的根路径
 *
 * @return string
 */
function getRootPath()
{
    return realpath(__DIR__ . '/..');
}
/**
 * 获取数据库文件的完整路径
 *
 * @return string
 */
function getDatabasePath()
{
    return getRootPath() . '/../data/data.sqlite';
}
/**
 * 获取SQLite连接的DSN
 *
 * @return string
 */
function getDsn()
{
    return 'sqlite:' . getDatabasePath();
}
/**
 * 获取用于数据库访问的PDO对象
 *
 * @return \PDO
 */
function getPDO()
{
    $pdo = new PDO(getDsn());
    // 需要在SQLite中手动启用外键约束
    $result = $pdo->query('PRAGMA foreign_keys = ON');
    if ($result === false)
    {
        throw new Exception('无法打开外键约束');
    }
    return $pdo;
}

/**
 * 转义HTML，因此可以安全输出
 *
 * @param string $html
 * @return string
 */
function htmlEscape($html)
{
    return htmlspecialchars($html, ENT_HTML5, 'UTF-8');
}

function convertSqlDate($sqlDate)
{
    //时间转换
    $date = DateTime::createFromFormat('Y-m-d H:i:s',$sqlDate);
    return $date->format('d,M,Y H:i');
}

function getSqlDateForNow()
{
    return date('Y-m-d H:i:s');
}

/**
 * Gets a list of posts in reverse order
 *
 * @param PDO $pdo
 * @return array
 */
function getAllPosts(PDO $pdo)
{
    $stmt = $pdo->query(
    'SELECT
        id, title, created_at, body,
        (SELECT COUNT(*) FROM comment WHERE comment.post_id = post.id) comment_count
    FROM
        post
    ORDER BY
        created_at DESC'
    );
    if ($stmt === false)
    {
        throw new Exception('运行此查询时出现问题');
    }
    return $stmt->fetchAll(PDO::FETCH_ASSOC);


}

/**
 * 将不安全的文本转换为安全的，分段的HTML
 *
 * @param string $text
 * @return string
 */
function convertNewlinesToParagraphs($text)
{
    $escaped = htmlEscape($text);
    return '<p>' . str_replace("\n", "</p><p>", $escaped) . '</p>';
}
function redirectAndExit($script)
{
    // 获取相对于域的URL（例如/blog/whatever.php或/whatever.php）并工作
    // 移出资料夹（例如/ blog /或/）。
    $relativeUrl = $_SERVER['PHP_SELF'];
    $urlFolder = substr($relativeUrl, 0, strrpos($relativeUrl, '/') + 1);
    //重定向到完整URL（
    $host = $_SERVER['HTTP_HOST'];
    $fullUrl = 'http://' . $host . $urlFolder . $script;
    header('Location: ' . $fullUrl);
    exit();
}


/**
 * 返回指定帖子的所有评论 封装
 * @param PDO $pdo
 * @param integer $postId
 * @return array
 */
function getCommentsForPost(PDO $pdo,$postId)
{
    $sql = "
        SELECT
            id, name, text, created_at, website
        FROM
            comment
        WHERE
            post_id = :post_id
    ";
    $stmt = $pdo->prepare($sql);
    $stmt->execute(
        array('post_id' => $postId, )
    );
    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

function tryLogin(PDO $pdo, $username, $password)
{
    $sql = "
        SELECT
            password
        FROM
            user
        WHERE
            username = :username
            AND is_enabled = 1

    ";
    $stmt = $pdo->prepare($sql);
    $stmt->execute(
        array('username' => $username, )
    );
    $hash = $stmt->fetchColumn();
    // 从此行获取哈希，然后使用第三方哈希库进行检查
    $success = password_verify($password, $hash);
    return $success;
}
/**
 * 登录用户
 * 为了安全起见，我们要求PHP重新生成Cookie
 *
 * @param string $username
 */
function login($username)
{
    //在不修改当前会话中数据的前提下使用新的 ID 替换原有会话 ID。
    session_regenerate_id();
    $_SESSION['logged_in_username'] = $username;
}

function isLoggedIn()
{
    return isset($_SESSION['logged_in_username']);
}

function getAuthUser()
{
    return isLoggedIn() ? $_SESSION['logged_in_username'] : null;
}
/**
 * 注销用户
 */
function logout()
{
    unset($_SESSION['logged_in_username']);
}

/**
 * 查找当前身份验证用户的user_id
 */
function getAuthUserId(PDO $pdo)
{
    // 如果没有登录用户，则返回null
    if (!isLoggedIn())
    {
        return null;
    }
    $sql = "
        SELECT
            id
        FROM
            user
        WHERE
            username = :username
            AND is_enabled = 1

    ";
    $stmt = $pdo->prepare($sql);
    $stmt->execute(
        array(
            'username' => getAuthUser()
        )
    );
    return $stmt->fetchColumn();
}